package com.bfxy.rabbitmq.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * Created by deng_wb on 2020/3/14
 */
@SuppressWarnings("all")
public class MyConsumer extends DefaultConsumer {
    /**
     * Constructs a new instance and records its association to the passed-in channel.
     *
     * @param channel the channel to which this consumer is attached
     */


    private Channel channel;

    public MyConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }


    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

        System.err.println("-----------ack message----------");
        System.err.println("body: " + new String(body));

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Integer num = (Integer) properties.getHeaders().get("num");

        if (num==0){
            // 投递失败,消息重回队列
            channel.basicNack(envelope.getDeliveryTag(),false,true);
        }else{
            // 手动签收
            channel.basicAck(envelope.getDeliveryTag(),false);
        }



    }
}
